import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../providers/wallet_provider.dart';
import '../constants/wallet_constants.dart';
import '../widgets/network_selector_bottom_sheet.dart';

/// 创建钱包页面
class CreateWalletPage extends StatefulWidget {
  const CreateWalletPage({Key? key}) : super(key: key);

  @override
  State<CreateWalletPage> createState() => _CreateWalletPageState();
}

class _CreateWalletPageState extends State<CreateWalletPage> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  String _selectedNetwork = 'ethereum';
  String? _generatedMnemonic;
  bool _isGenerating = false;
  bool _showMnemonic = false;
  bool _isInitializing = true;
  bool _isCreating = false; // 添加创建中状态

  @override
  void initState() {
    super.initState();
    print('🔄 创建钱包页面初始化 - 清理旧数据并生成新助记词');
    // 每次进入页面都重置状态并生成新助记词
    _resetAndInitialize();
  }

  /// 重置状态并初始化
  Future<void> _resetAndInitialize() async {
    // 清理之前的数据
    _nameController.clear();
    _selectedNetwork = 'ethereum';
    _generatedMnemonic = null;
    _isGenerating = false;
    _showMnemonic = false;
    _isInitializing = true;
    _isCreating = false; // 重置创建状态
    
    print('✅ 状态已重置');
    
    // 生成新助记词
    await _initializeMnemonic();
  }

  Future<void> _initializeMnemonic() async {
    setState(() {
      _isInitializing = true;
    });

    try {
      print('🔄 开始生成新助记词...');
      // 异步生成助记词
      await Future.delayed(const Duration(milliseconds: 100)); // 让 UI 先渲染
      final walletProvider = context.read<WalletProvider>();
      final mnemonic = await walletProvider.generateMnemonic();
      
      print('✅ 助记词生成成功: ${mnemonic.split(' ').length} 个单词');
      
      if (mounted) {
        setState(() {
          _generatedMnemonic = mnemonic;
          _isInitializing = false;
        });
      }
    } catch (e) {
      print('❌ 生成助记词失败: $e');
      if (mounted) {
        setState(() {
          _isInitializing = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('生成助记词失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  void dispose() {
    print('🗑️ 创建钱包页面销毁 - 清理资源');
    _nameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF0A0E27),
      appBar: AppBar(
        title: const Text(
          '创建钱包',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: const Color(0xFF0A0E27),
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题
              const Text(
                '创建新的数字钱包',
                style: TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              const SizedBox(height: 8),
              const Text(
                '请填写钱包信息并安全保存助记词',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.white70,
                ),
              ),
              const SizedBox(height: 32),

              // 钱包名称
              _buildInputField(
                label: '钱包名称',
                controller: _nameController,
                hintText: '请输入钱包名称',
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '请输入钱包名称';
                  }
                  if (value.trim().length < 2) {
                    return '钱包名称至少2个字符';
                  }
                  return null;
                },
              ),

              const SizedBox(height: 24),

              // 网络选择
              _buildNetworkSelector(),

              const SizedBox(height: 32),

              // 生成助记词按钮
              SizedBox(
                width: double.infinity,
                child: ElevatedButton.icon(
                  onPressed: _isGenerating ? null : _generateMnemonic,
                  icon: _isGenerating
                      ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                          ),
                        )
                      : const Icon(Icons.security),
                  label: Text(_isGenerating ? '生成中...' : '生成助记词'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF6C5CE7),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                ),
              ),

              const SizedBox(height: 24),

              // 助记词显示
              if (_generatedMnemonic != null) _buildMnemonicDisplay(),

              const SizedBox(height: 32),

              // 创建钱包按钮 - 始终显示，未勾选时置灰
              if (_generatedMnemonic != null)
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton.icon(
                    onPressed: (_showMnemonic && !_isCreating) ? _createWallet : null,
                    icon: _isCreating
                        ? const SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                          )
                        : const Icon(Icons.check),
                    label: Text(_isCreating ? '创建中...' : '创建钱包'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _showMnemonic ? Colors.green : Colors.grey,
                      foregroundColor: Colors.white,
                      disabledBackgroundColor: Colors.grey.withOpacity(0.5),
                      disabledForegroundColor: Colors.white.withOpacity(0.5),
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建输入框
  Widget _buildInputField({
    required String label,
    required TextEditingController controller,
    String? hintText,
    String? Function(String?)? validator,
    bool obscureText = false,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: controller,
          validator: validator,
          obscureText: obscureText,
          autovalidateMode: AutovalidateMode.onUserInteraction, // 添加自动验证模式
          style: const TextStyle(color: Colors.white),
          decoration: InputDecoration(
            hintText: hintText,
            hintStyle: const TextStyle(color: Colors.white54),
            filled: true,
            fillColor: const Color(0xFF1E2139),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide(color: Colors.white.withOpacity(0.1)),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: Color(0xFF6C5CE7)),
            ),
            focusedErrorBorder: OutlineInputBorder( // 添加聚焦错误状态边框
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: Colors.red, width: 2),
            ),
            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: Colors.red),
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 16,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建网络选择器
  Widget _buildNetworkSelector() {
    final selectedNetwork = WalletConstants.supportedNetworks[_selectedNetwork];
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '选择网络',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: 8),
        Material(
          color: const Color(0xFF1E2139),
          borderRadius: BorderRadius.circular(12),
          child: InkWell(
            onTap: _showNetworkBottomSheet,
            borderRadius: BorderRadius.circular(12),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.white.withOpacity(0.1)),
              ),
              child: Row(
                children: [
                  Container(
                    width: 8,
                    height: 8,
                    decoration: const BoxDecoration(
                      color: Color(0xFF6C5CE7),
                      shape: BoxShape.circle,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      selectedNetwork?.name ?? 'Unknown',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                      ),
                    ),
                  ),
                  const Icon(
                    Icons.arrow_drop_down,
                    color: Colors.white70,
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 显示网络选择底部弹出框
  Future<void> _showNetworkBottomSheet() async {
    final selectedNetwork = await NetworkSelectorBottomSheet.show(
      context,
      currentNetwork: _selectedNetwork,
    );
    
    if (selectedNetwork != null) {
      setState(() {
        _selectedNetwork = selectedNetwork;
      });
    }
  }

  /// 构建助记词显示
  Widget _buildMnemonicDisplay() {
    final words = _generatedMnemonic!.split(' ');
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            const Icon(Icons.security, color: Color(0xFF6C5CE7)),
            const SizedBox(width: 8),
            const Text(
              '助记词',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            const Spacer(),
            IconButton(
              onPressed: _copyMnemonic,
              icon: const Icon(Icons.copy, color: Color(0xFF6C5CE7)),
              tooltip: '复制助记词',
            ),
          ],
        ),
        const SizedBox(height: 16),
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: const Color(0xFF1E2139),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: const Color(0xFF6C5CE7).withOpacity(0.3)),
          ),
          child: Wrap(
            spacing: 8,
            runSpacing: 8,
            children: words.asMap().entries.map((entry) {
              final index = entry.key;
              final word = entry.value;
              return Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                decoration: BoxDecoration(
                  color: const Color(0xFF6C5CE7).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: const Color(0xFF6C5CE7).withOpacity(0.3)),
                ),
                child: Text(
                  '${index + 1}. $word',
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              );
            }).toList(),
          ),
        ),
        const SizedBox(height: 16),
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.orange.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.orange.withOpacity(0.3)),
          ),
          child: Row(
            children: [
              const Icon(Icons.warning, color: Colors.orange),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '重要提示',
                      style: TextStyle(
                        color: Colors.orange,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    const Text(
                      '请安全保存助记词，不要截图或发送给他人。助记词是恢复钱包的唯一方式。',
                      style: TextStyle(
                        color: Colors.white70,
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        Row(
          children: [
            Checkbox(
              value: _showMnemonic,
              onChanged: (value) {
                setState(() {
                  _showMnemonic = value ?? false;
                });
              },
              activeColor: const Color(0xFF6C5CE7),
            ),
            const Expanded(
              child: Text(
                '我已安全保存助记词，确认创建钱包',
                style: TextStyle(color: Colors.white70),
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 生成助记词
  Future<void> _generateMnemonic() async {
    setState(() {
      _isGenerating = true;
    });

    try {
      // 模拟生成过程
      await Future.delayed(const Duration(seconds: 1));
      
      // 这里应该调用 WalletService 生成助记词
      // 为了演示，使用固定的助记词
      _generatedMnemonic = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
      
      setState(() {
        _showMnemonic = true;
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('生成助记词失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      setState(() {
        _isGenerating = false;
      });
    }
  }

  /// 复制助记词
  void _copyMnemonic() {
    if (_generatedMnemonic != null) {
      Clipboard.setData(ClipboardData(text: _generatedMnemonic!));
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('助记词已复制到剪贴板'),
          backgroundColor: Colors.green,
        ),
      );
    }
  }

  /// 创建钱包
  Future<void> _createWallet() async {
    // 验证表单
    if (!_formKey.currentState!.validate()) {
      print('❌ 表单验证失败');
      return;
    }
    
    // 检查是否已确认保存助记词
    if (!_showMnemonic) {
      print('⚠️ 用户未确认保存助记词');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请确认已安全保存助记词'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // 防止重复点击
    if (_isCreating) {
      print('⚠️ 正在创建中，忽略重复点击');
      return;
    }

    // 设置创建中状态
    setState(() {
      _isCreating = true;
    });

    print('==================== 开始创建钱包 ====================');
    print('📝 钱包名称: ${_nameController.text.trim()}');
    print('🌐 网络: $_selectedNetwork');
    print('🔑 助记词: ${_generatedMnemonic?.split(' ').length ?? 0} 个单词');

    try {
      final startTime = DateTime.now();
      print('⏱️ 创建开始时间: ${startTime.toIso8601String()}');

      // 创建钱包，但不立即加载余额（返回主页后再加载）
      await context.read<WalletProvider>().createWallet(
        name: _nameController.text.trim(),
        networkId: _selectedNetwork,
        mnemonic: _generatedMnemonic,
        loadDataImmediately: false, // 不立即查询余额，加快创建速度
      );

      final endTime = DateTime.now();
      final duration = endTime.difference(startTime);
      print('⏱️ 创建完成时间: ${endTime.toIso8601String()}');
      print('⏱️ 耗时: ${duration.inMilliseconds} ms');
      print('✅ 钱包创建成功！');
      print('==================================================');

      if (mounted) {
        // 返回上一页
        Navigator.pop(context);
        
        // 显示成功提示
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('✅ 钱包创建成功'),
            backgroundColor: Colors.green,
            duration: Duration(seconds: 2),
          ),
        );
        
        // 返回主页后，异步加载钱包数据
        Future.delayed(const Duration(milliseconds: 300), () {
          if (mounted) {
            context.read<WalletProvider>().refreshWalletData();
          }
        });
      }
    } catch (e, stackTrace) {
      print('❌ 创建钱包失败！');
      print('❌ 错误类型: ${e.runtimeType}');
      print('❌ 错误信息: $e');
      print('❌ 堆栈跟踪: $stackTrace');
      print('==================================================');

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('创建钱包失败: $e'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    } finally {
      // 恢复按钮状态
      if (mounted) {
        setState(() {
          _isCreating = false;
        });
        print('🔓 按钮状态已恢复');
      }
    }
  }
}
